<?php
declare (strict_types=1);

namespace app\controller;

use think\Request;
use app\model\Menu;
use app\model\Role;
use app\model\UserLog;
use app\model\Config;
use think\facade\View;
use think\Model;
use think\facade\Db;
class System
{

    public function menu_list(Menu $Menu)
    {
        $data = Menu::cache('menu_list_all')->order('sort')->select()->toArray();
        foreach ($data as &$d) {
            $d['open'] = 1;
        }
        if (input('t') == 'json')
            return json(['msg' => '', 'code' => 0, 'data' => $data, 'count' => count($data)]);

        return view('', $data);
    }

    public function menu_edit(Menu $Menu)
    {
        // 上级菜单数据
        if (input('p_tree') == 'json') {
            $p_tree = [];
            $p_tree = $Menu->getMenuTree(0, 'children', ['spread' => 0]);
            return json(['code' => 0, 'data' => $p_tree]);
        }
        // 默认数据
        $data = [
            'pid' => 0,
            'is_menu' => '1',
            'status' => 'on',
        ];
        if (input('id')) {
            $data = Menu::find(input('id'));
            if ($data['pid']) {
                $p_data = Menu::find($data['pid']);
                if ($p_data) {
                    $data['p_val'] = $p_data->title;
                }
            }
        } elseif (input('pid')) {
            $p_data = Menu::find(input('pid'));
            if ($p_data) {
                $data['pid'] = $p_data->id;
                $data['p_val'] = $p_data->title;
            }
        }
        $menuList = $Menu::cache('menu_list')->where(['status'=>'on'])->select()->toArray();
        return view('', ['data' => $data, 'menu_list' => $menuList]);
    }

    public function menu_save(Menu $Menu)
    {
        $data = [
            'id' => input('id/d', 0),
            'pid' => input('pid/d', 0),
            'title' => input('title/s'),
            'icon' => input('icon/s'),
            'href' => input('href/s'),
            'target' => input('target/s', '_self'),
            'status' => input('status/s') == 'on' ? 'on' : 'off',
            'is_menu' => input('is_menu/s') == 'on' ? 1 : 0,
            'sort' => input('sort/d', 0),
        ];
        $p_menu = Menu::find($data['pid']);
        if ($p_menu) $data['lv'] = $p_menu['lv'] + 1;
        if ($data['id'] < 1) { // 新增
            $r = Menu::create($data);
        } else { // 修改
            $r = Menu::find($data['id'])->update($data);
        }
        if (empty($r))
            return json(['msg' => '保存失败', 'code' => 1]);
        cache('menu_list_all', NULL);
        cache('menu_list', NULL);
        cache('menu_tree_all', NULL);
        cache('menu_tree', NULL);
        return json(['msg' => '保存成功', 'code' => 0, 'content' => $data, 'sql'=>Menu::getLastSql()]);
    }

    public function menu_del(Menu $Menu)
    {
        $id = input('id/d', 0);
        if (empty($id))
            return json(['msg' => '未找到菜单', 'code' => 1]);
        if (Menu::destroy($id)) {
            cache('menu_list_all', NULL);
            cache('menu_list', NULL);
            cache('menu_tree_all', NULL);
            cache('menu_tree', NULL);
            return json(['msg' => '删除成功', 'code' => 0]);
        }
        else return json(['msg' => '删除失败', 'code' => 1]);
    }

    public function base(Config $conf)
    {
        if (request()->isPost()) {
            $data = input();
            $rows = [];
            foreach ($data as $key => $val) {
                $row = [];
                $r = Config::where(['key' => $key])->find();
                $row['id'] = empty($r) ? null : $r->id;
                $row['group'] = 'meta';
                $row['key'] = $key;
                $row['value'] = $val;
                $rows[] = $row;
            }
            $r = $conf->saveAll($rows);
            if ($r) {
                return json(['code' => 0, 'msg' => '保存成功']);
            }
            return json(['code' => 1, '保存失败']);
        }
        $conf = Config::where(['group' => 'meta'])->select();
        $data = [];
        foreach ($conf as $val) {
            $data[$val['key']] = $val['value'];
        }
        return view('', ['data' => $data]);
    }

    public function qywx_conf()
    {
        return view('', ['qywx' => config('qywx')]);
    }

    public function user_role(Menu $Menu, Role $Role)
    {
        $arrMenus = Menu::order('lv, id')->select()->toArray();
        if (input('t') == 'json') {
            $data = Role::where(['status' => '1'])->order('id, sort desc')->select()->toArray();
            foreach ($data as &$d) {
                $d['open'] = 1;
                $d['rules_val'] = [];
                $rules = $d['rules'];
                if (!empty($rules)) {
                    foreach ($arrMenus as $row) {
                        if (in_array($row['id'], $rules)) {
                            $d['rules_val'][] = [
                                'id' => $row['id'],
                                'lv' => $row['lv'],
                                'title' => $row['title'],
                            ];
                        }
                    }
                }
            }
            return json([
                'code' => 0,
                'msg' => '',
                'count' => count($data),
                'data' => $data
            ]);
        }
        return view();
    }

    public function role_edit(Role $Role, Menu $Menu)
    {
        // 上级菜单数据
        if (input('p_tree') == 'json') {
            $p_tree = [];
            $p_tree = $Menu->getMenuTreeAll(0, 'children', ['spread' => 1]);
            return json(['code' => 0, 'data' => $p_tree]);
        }
        if (input('t') == 'json') {
            $data = Role::find(input('id/d'));
            return json($data);
        }
        // 默认数据
        $data = [];
        if (input('id')) {
            $data = Role::find(input('id/d'));
        }
        $menuList = Menu::select();
        $data['tree_vals'] = empty($data['tree_vals']) ? '' : json_encode($data['tree_vals'], 1);
        return view('', ['data' => $data, 'menu_list' => $menuList]);
    }

    public function role_save(Role $Role)
    {
        $data = [
            'id' => input('id/d', 0),
            'name' => input('name/s'),
            'rules' => input('rules/a'),
            'tree_vals' => input('tree_vals/a'),
            'sort' => input('sort/d', 0),
        ];
        if ($data['id'] < 1) { // 新增
            $r = Role::create($data);
        } else { // 修改
            $r = Role::find($data['id'])->update($data);
        }
        if (empty($r))
            return json(['msg' => '保存失败', 'code' => 1]);
        return json(['msg' => '保存成功', 'code' => 0]);
    }

    public function role_del()
    {
        $id = input('id/d', 0);
        if (empty($id))
            return json(['msg' => '未找到角色', 'code' => 1]);
        if (Role::destroy($id))
            return json(['msg' => '删除成功', 'code' => 0]);
        else return json(['msg' => '删除失败', 'code' => 1]);
    }

    public function logs(UserLog $UserLog)
    {
        if (input('t') == 'json') {
            $pn = request()->get('page/d', 1);
            $ps = request()->get('limit/d', 15);
            if (input('a') == 'user_logs') { // 用户日志
                
                $cnt = UserLog::count();
                $rows = UserLog::with(['user', 'role'])->page($pn, $ps)->order('id desc')->select();
                $data = [ 'code' => 0, 'count' => $cnt, 'data' => $rows ];
            } else { // 系统日志
                $cnt = Db::name('logs')->count('id');
                $rows = Db::name('logs')->alias('l')
                ->field('l.*,u.username,r.name role_name')
                ->join('user u','l.uid = u.id','LEFT')
                ->join('role r','l.role_id = r.id','LEFT')
                ->page($pn, $ps)->order('l.id desc')->select();
                
                $data = [ 'code' => 0, 'count' => $cnt, 'data' => $rows ];
            }

            return json($data);
        }
        
        return view();
    }
    
    //字节跳动Api配置
    public function zijie_api(){
        $confing = new Config();
        if(request()->isPost() && input('t')=='json'){
            $data = input('post.');
            foreach ($data as $k=>$v){
                $r = Config::where(['key' => $k])->find();
                $arr['id'] = empty($r) ? null : $r->id;
                $arr['group'] = 'zjapi';
                $arr['key'] = $k;
                $arr['value'] = $v;
                $d[] = $arr;
            }
            $r = $confing->saveAll($d);
            if(!empty($r)){
                return json(['code'=>1,'msg'=>'提交成功']);
            }else{
                return json(['code'=>0,'msg'=>'提交失败']);
            }
            
        }else{
            $data = Config::where('group','zjapi')->select();
            foreach ($data as $k=>$v){
                $d[$v['key']] = $v['value'];
            }
            
            View::assign('data',$d);
            return view();
        }
        
    }


















    
    
    

}
